<?php
declare (strict_types=1);

namespace app\admin\middleware;

use app\tool\Controller\TokenController;
use app\tool\Controller\CacheController;


use think\Response;
use think\Request;

use Closure;

class Token
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return \think\Response
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('token'); // 假设token是通过Authorization头部发送的
        if (!$token) {
            // 返回401 Unauthorized状态码和错误信息
            return Response::create(['code' => 401, 'msg' => 'header缺少Token,请登录'], 'json', 401);
        } else {
            $tokenDecode = TokenController::checkToken($token);
            if ($tokenDecode['status'] == 200) {
                $tokenUser = $this->tokenDecode($tokenDecode);
                if ($tokenUser) {
                    if (CacheController::get('user_' . $tokenUser['id']) != $token) {
                        return Response::create(['code' => 401, 'msg' => '缓存无效的Token,请去登录'], 'json', 401);
                    }
                } else {
                    return Response::create(['code' => 401, 'msg' => 'Token时间段无效,请去登录!'], 'json', 401);
                }
            } else {
                return Response::create(['code' => 401, 'msg' => '无效过期Token,请去登录!!'], 'json', 401);
            }
        }
        // 如果token存在，则继续执行下一个中间件或控制器
        return $next($request);
    }

    public function tokenDecode($tokenDecode)
    {

        $star = $tokenDecode['data']['iat'];
        $end = $tokenDecode['data']['exp'];
        if ($star < time() && time() < $end) {
            return $this->objToArray($tokenDecode['data']['data']);
        }
    }

    public function objToArray($obj)
    {
        return json_decode(json_encode($obj), true);
    }
}